import config from '@/utils/config.js'
import store from '@/vuex/store.js'
import SparkMD5 from 'spark-md5'
const getUrl = (url) => {
	return config.api_host + url
}
export const util = {
	imgUrl(url = "") {
		return rootUrl + url
	},
	getRequest({
		url = "",
		data = {}
	}) {
		return new Promise((resolve, reject) => {
			let user = uni.getStorageSync("userInfo") || {}
			let token = user.token || ""
			uni.request({
				url: getUrl(url),
				data,
				method: "GET",
				header: {
					"Content-Type": "application/x-www-form-urlencoded",
					"Token": token
				},
				success(res) {
					if (res.data.code === 1) {
						resolve(res.data)
					} else {
						uni.hideLoading()
						if(res.data.msg){
							uni.showToast({
								title: res.data.msg,
								icon: "none"
							})
						}
						if (res.data.code === 401) {
							store.commit("changeLogin")
						}
						reject(res.data)
					}
				},
				fail(e) {
					console.log(e);
					e.errMsg = '请稍后重试';
					uni.hideLoading()
					uni.showToast({
						// TODO: W
						title: e?.data?.msg??e.errMsg,
						icon: "none"
					})
					reject(e)
				}
			})
		})
		return promist
	},
	postRequest({
		url = "",
		data = {}
	}) {
		return new Promise((resolve, reject) => {
			let user = uni.getStorageSync("userInfo") || {}
			let token = user.token || ""
			uni.request({
				url: getUrl(url),
				data,
				header: {
					"Content-Type": "application/json",
					"Token": token
				},
				method: "POST",
				success(res) {
					console.log(res.data)
					if (res.data.code === 1) {
						resolve(res.data)
					} else {
						if (res.data.code === 401) {
							store.commit("changeLogin")
						}
						
						reject(res.data)
					}
				},
				fail(e) {
					uni.hideLoading()
					reject(e)
				}
			})
		})
		return promist
	},
	uploadFile(url = "") {
		let user = uni.getStorageSync("userInfo") || {}
		let token = user.token || ""
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				success(fres) {
					uni.showLoading({
						title: "上传中..."
					})
					let reader = null;
					let real_path = '';
					//采用客户端直传
					let category = 'user'
					let path = fres.tempFilePaths[0]
					let size = fres.tempFiles[0].size
					let splitArr = path.split("/");
					let name = splitArr[splitArr.length - 1];
					// #ifdef APP
					reader = new plus.io.FileReader()
					real_path = plus.io.convertLocalFileSystemURL(path);
					reader.readAsDataURL(real_path)// 以URL格式读取文件
					// #endif
					// #ifdef H5
					reader = new FileReader();
					real_path = path;
					reader.readAsDataURL(fres.tempFiles[0])// 以URL格式读取文件

					// #endif
					reader.onerror = (e) => {
						uni.hideLoading()
						uni.showToast({
							// TODO: W
							title: '上传失败',
							icon: "none"
						})
					}
					reader.onload = async (e) => {
						//进行MD5加密
						let spark = new SparkMD5()
						spark.appendBinary(e.target.result)
						let md5 = spark.end()
						let type = e.target.result.split('data:')[1];
						type = type.split(';base64,')[0];
						
						let width = 0
						let height = 0
						if (type.split('/')[0] == 'image') {
							let img_info = await util.getImgInfo(real_path)
							width = img_info.width
							height = img_info.height
						}
						util.postRequest({
							url:'v1/public_/getOssToken'
						}).then(res => {
							let oss_token = res.data.token
							util.postRequest({
								url:'v1/public_/getOssParams',
								data: {
									method:'POST',
									category:category,
									md5:md5,
									name:name,
									type:type,
									size:size,
									chunk:0,
									chunksize:4194304,
									aliosstoken: oss_token
								}
							}).then(res => {
								let params = res.data
								uni.uploadFile({
									url : params.uploadurl,
									name: "file",
									filePath: real_path,
									formData: {
										aliosstoken: oss_token,
										id: params.id,
										key: params.key,
										policy: params.policy,
										signature: params.signature,
										expire: params.expire,
										callback: '',
										OSSAccessKeyId: params.OSSAccessKeyId,
										success_action_status: params.success_action_status,
										category: category
									},
									success(res) {
										if (res.statusCode == 200) {
											util.postRequest({
												url:'v1/public_/notifyOss',
												data: {
													name: name,
													url: '/'+ params.key,
													md5: md5,
													size: size,
													width: width,
													height: height,
													type: type,
													category: category,
													aliosstoken: oss_token
												}
											}).then(res => {
												resolve(res)
												// 这里上传成功了
												uni.hideLoading()
											}).catch(err=> {
												uni.hideLoading()
											})
										} else {
											uni.showToast({
												// TODO: W
												title: '上传失败',
												icon: "none"
											})
										}
									},
									complete() {
										// uni.hideLoading()
									}
								})
							}).catch(err => {
								console.log(err)
								uni.hideLoading()
							})
						}).catch(err => {
							console.log(err)
							uni.hideLoading()
						})

					};
					
					
					
					//以下是备份
					// uni.uploadFile({
					// 	url: getUrl("v1/public_/upload"),
					// 	name: "file",
					// 	formData: {
					// 		category: "user",
					// 	},
					// 	header: {
					// 		"Token": token
					// 	},
					// 	filePath: path,
					// 	success(res) {
					// 		let data = JSON.parse(res.data)
					// 		resolve(data)
					// 	},
					// 	complete() {
					// 		uni.hideLoading()
					// 	}
					// })
				},
				fail(e) {
					console.log(e)
					let title = ""
					if ((e.code === 11 || e.code === 12) && e.errMsg.indexOf("No Permission")>-1) {
						uni.showModal({
							title: "提示",
							content: "未授权使用相机/读取文件，请先授权后再试",
							success(res) {
								if (res.confirm) {
									// #ifdef APP-PLUS
									const Settings = plus.android.importClass(
										'android.provider.Settings')
									const ACTION_APPLICATION_DETAILS_SETTINGS = Settings
										.ACTION_APPLICATION_DETAILS_SETTINGS

									const Uri = plus.android.importClass('android.net.Uri')

									const Intent = plus.android.importClass(
										'android.content.Intent')
									const intent = new Intent(
										ACTION_APPLICATION_DETAILS_SETTINGS)
									const packageName = 'com.baodika.app' // 替换为目标应用程序的包名
									const uri = Uri.parse('package:' + packageName)
									intent.setData(uri)

									const Activity = plus.android.importClass(
										'android.app.Activity')
									const currentActivity = plus.android
										.runtimeMainActivity()
									currentActivity.startActivity(intent)
									// #endif
								}
							}
						})
					}
					reject(false)
				}
			})
		})
	},
	getImgInfo(path) {
		return new Promise((resolve,reject) => {
			uni.getImageInfo({
				src: path,
				success: (res) => {
					resolve(res)
					return res
				},
				fail: (err) => {
					reject(err)
				},
				complete: (res) => {},
			  })
		})
	},
	uploadVideo(url = "") {
		let user = uni.getStorageSync("userInfo") || {}
		let token = user.token || ""
		return new Promise((resolve, reject) => {
			uni.chooseVideo({
				count: 1,
				success(fres) {
					uni.showLoading({
						title: "上传中..."
					})
					//采用客户端直传
					let category = 'user'
					let path = fres.tempFilePath
					let size = fres.size
					let splitArr = path.split("/");
					let name = splitArr[splitArr.length - 1];
					let reader = new plus.io.FileReader()
					let real_path = plus.io.convertLocalFileSystemURL(path);
					reader.readAsDataURL(real_path)// 以URL格式读取文件
					reader.onerror = (e) => {
						uni.hideLoading()
						uni.showToast({
							// TODO: W
							title: '上传失败',
							icon: "none"
						})
					}
					reader.onload = async (e) => {
						//进行MD5加密
						let spark = new SparkMD5()
						spark.appendBinary(e.target.result)
						let md5 = spark.end()
						let type = e.target.result.split('data:')[1];
						type = type.split(';base64,')[0];
						let width = fres.width
						let height = fres.height
						// console.log(type)
						// return
						// if (type.split('/')[0] == 'image') {
						// 	let img_info = await util.getImgInfo(real_path)
						// 	width = img_info.width
						// 	height = img_info.height
						// }
						util.postRequest({
							url:'v1/public_/getOssToken'
						}).then(res => {
							let oss_token = res.data.token
							util.postRequest({
								url:'v1/public_/getOssParams',
								data: {
									method:'POST',
									category:category,
									md5:md5,
									name:name,
									type:type,
									size:size,
									chunk:0,
									chunksize:4194304,
									aliosstoken: oss_token
								}
							}).then(res => {
								let params = res.data
								uni.uploadFile({
									url : params.uploadurl,
									name: "file",
									filePath: real_path,
									formData: {
										aliosstoken: oss_token,
										id: params.id,
										key: params.key,
										policy: params.policy,
										signature: params.signature,
										expire: params.expire,
										callback: '',
										OSSAccessKeyId: params.OSSAccessKeyId,
										success_action_status: params.success_action_status,
										category: category
									},
									success(res) {
										if (res.statusCode == 200) {
											util.postRequest({
												url:'v1/public_/notifyOss',
												data: {
													name: name,
													url: '/' + params.key,
													md5: md5,
													size: size,
													width: width,
													height: height,
													type: type,
													category: category,
													aliosstoken: oss_token
												}
											}).then(res => {
												resolve(res)
												// 这里上传成功了
												uni.hideLoading()
											}).catch(err=> {
												uni.hideLoading()
											})
										} else {
											uni.showToast({
												// TODO: W
												title: '上传失败',
												icon: "none"
											})
										}
									},
									complete() {
										// uni.hideLoading()
									}
								})
							}).catch(err => {
								console.log(err)
								uni.hideLoading()
							})
						}).catch(err => {
							console.log(err)
							uni.hideLoading()
						})

					}

					


					//备份
					// let path = fres.tempFilePath
					// uni.uploadFile({
					// 	url: getUrl("v1/public_/upload"),
					// 	name: "file",
					// 	formData: {
					// 		category: "user",
					// 	},
					// 	header: {
					// 		"Token": token
					// 	},
					// 	filePath: path,
					// 	success(res) {
					// 		let data = JSON.parse(res.data)
					// 		resolve(data)
					// 	},
					// 	complete() {
					// 		uni.hideLoading()
					// 	}
					// })
				},
				fail(e) {
					console.log(e)
					let title = ""
					if ((e.code === 11 || e.code === 12) && e.errMsg.indexOf("No Permission")>-1) {
						uni.showModal({
							title: "提示",
							content: "未授权使用相机/读取文件，请先授权后再试",
							success(res) {
								if (res.confirm) {
									// #ifdef APP-PLUS
									const Settings = plus.android.importClass(
										'android.provider.Settings')
									const ACTION_APPLICATION_DETAILS_SETTINGS = Settings
										.ACTION_APPLICATION_DETAILS_SETTINGS
	
									const Uri = plus.android.importClass('android.net.Uri')
	
									const Intent = plus.android.importClass(
										'android.content.Intent')
									const intent = new Intent(
										ACTION_APPLICATION_DETAILS_SETTINGS)
									const packageName = 'com.baodika.app' // 替换为目标应用程序的包名
									const uri = Uri.parse('package:' + packageName)
									intent.setData(uri)
	
									const Activity = plus.android.importClass(
										'android.app.Activity')
									const currentActivity = plus.android
										.runtimeMainActivity()
									currentActivity.startActivity(intent)
									// #endif
								}
							}
						})
					}
					reject(false)
				}
			})
		})
	},
}
export default {
	util
}